package com.allen;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.cglib.beans.BeanMap;

import org.apache.poi.ss.usermodel.Cell;

import com.allen.excelUtils.column.Column;
import com.allen.excelUtils.exception.FormatException;
import com.allen.excelUtils.format.RFormatter;
import com.allen.excelUtils.format.RowFormatter;
import com.allen.excelUtils.row.DataRow;
import com.esotericsoftware.reflectasm.MethodAccess;

public class RowFormatterImpl3<T> extends RFormatter implements RowFormatter<T> {
	final Class<T> cls;
	BeanMap beanMap;
	Field[] fields;
	Map<String, Column> columnMap;
	MethodAccess methodAccess;
	Map<String, String> methods =  new HashMap<String, String>();
	public RowFormatterImpl3(Class<T> cls){
		this.cls = cls;
		fields = cls.getDeclaredFields();
		Field.setAccessible(fields, true);
		try {
			for(Field field : fields){
				String fldName = field.getName();
				fldName = fldName.substring(0, 1).toUpperCase()+fldName.replaceFirst("\\w","");
				methods.put(field.getName(), "set"+fldName);
			}
			methodAccess = MethodAccess.get(cls);
		} catch (Exception e) {
			throw new FormatException(e);
		}
	}
	
	public T getInstance() throws InstantiationException, IllegalAccessException{
		return cls.newInstance();
	}
	
	@Override
	public T format(DataRow row) throws FormatException {
		columnMap = row.getColumnMap();
		try {
			T obj = getInstance();
			for (Entry<String, Column> col : columnMap.entrySet()) {
				Cell cell = row.getCell(col.getKey());
				methodAccess.invoke(obj, methods.get(col.getKey()), getValue(cell));
			}
			return obj;
		} catch (Exception e) {
			throw new FormatException(e);
		}
	}
}
